package cn.edu.xmu.oomall.customer.dao;


import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.oomall.customer.dao.bo.Coupon;
import cn.edu.xmu.oomall.customer.mapper.CouponPoMapper;
import cn.edu.xmu.oomall.customer.mapper.po.CouponPo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Repository
@RefreshScope
@RequiredArgsConstructor
public class CouponDao {

    private final CouponPoMapper couponPoMapper;


    public List<Coupon> retrieveCouponByCustomerIdAndActId(Long customerId, Long actId) {
        List<CouponPo> pos = couponPoMapper.retrieveCouponByCustomerIdAndActId(customerId, actId);
        if (pos.isEmpty()) {
            return null;
        } else {
            throw new BusinessException(ReturnNo.COUPON_EXIST, String.format(ReturnNo.COUPON_EXIST.getMessage(), "优惠券已领取", actId));
        }
    }


    public Long findById() {
        Long count = couponPoMapper.findCountById();
        return count;
    }

    public void insert(Coupon bo, UserDto user) {
        bo.setCreator(user);
        bo.setGmtCreate(LocalDateTime.now());
        CouponPo po = CloneFactory.copy(new CouponPo(), bo);
        couponPoMapper.save(po);
    }

    public List<Coupon> retrieveCoupons(Long used, UserDto user, Integer page, Integer pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        user.setId(6L);
        List<CouponPo> pos = this.couponPoMapper.findByCustomerId(user.getId(), pageable);
        return pos.stream().map(po -> {
            Coupon bo = CloneFactory.copy(new Coupon(), po);
//            bo = build(bo);
            return bo;
        }).collect(Collectors.toList());
    }
}
